﻿using AutoMapper;
using MaterialManagement.API.Application.Command.ERP;
using MaterialManagement.Domain.ERP;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Implement;
using MaterialManagement.Infrastructure.Interface;
using MediatR;
using Process.Domain;
using ProductionLine.Domain.Product;

namespace MaterialManagement.API.Application.Handler.ERP
{
    public class CreateProcessInspectionHandler : IRequestHandler<CreateProcessInspectionCommand, APIResult<int>>
    {
        private readonly DatabaseContext database;
        private readonly IMapper mapper;

        public CreateProcessInspectionHandler(DatabaseContext database,
                                              IMapper mapper)
        {
            this.database = database;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(CreateProcessInspectionCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = await database.SqlSugar.Queryable<ProcessInspectionModel>().FirstAsync(x => x.InspectionOrderCode == request.InspectionOrderCode);
            if (res != null)
            {
                result.Message = "已有此检验单";
                result.Code = APIEnum.Fail;
                return result;
            }
            await database.SqlSugar.Ado.BeginTranAsync();
            var model = mapper.Map<ProcessInspectionModel>(request);
            var s = await database.SqlSugar.Queryable<ProductionOrders>().FirstAsync(x => x.ProductionOrdersCode == model.ProductionOrderCode);
            var product = await database.SqlSugar.Queryable<ProductModel>().FirstAsync(x => x.ProductId.ToString() == s.ProductCode);
            if (model.InspectionQuantity == 0)
            {
                result.Message = "检验数量不能为 0";
                result.Code = APIEnum.Fail;
                return await Task.FromResult(result);
            }
            if ((double)model.QualifiedQuantity/ model.InspectionQuantity < 0.8)
            {
                model.State = false;
            }
            else
            {
                model.State = true;
                product.ProductQuantity = product.ProductQuantity + s.PlannedQuantity;
                await database.SqlSugar.Updateable(product).ExecuteCommandAsync();
            }
            model.UnqualifiedQuantity = model.InspectionQuantity - model.QualifiedQuantity;
            int r = database.SqlSugar.Insertable(model).ExecuteCommand();
            await database.SqlSugar.CommitTranAsync();
            if (r > 0)
            {
                result.Message = "添加成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "添加失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return await Task.FromResult(result);
        }
    }
}
